package com.exm.sql.filter;

import com.alibaba.fastjson2.JSON;
import com.exm.sql.config.CustomConfig;
import com.exm.sql.config.TokenContext;
import com.exm.sql.model.vo.ResponseResult;
import com.exm.sql.util.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import netscape.javascript.JSObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;


@Component
public class TokenFilter implements Filter {
    @Autowired
    private CustomConfig customConfig;



    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException, ServletException, IOException {




        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String requestURI = httpServletRequest.getRequestURI();

        // 如果请求是白名单中的 URL，则放行，不进行过滤
        if (isWhitelisted(requestURI)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }


        // 从请求头获取 token，假设 token 存储在 Authorization 头中
        String authorizationHeader = httpServletRequest.getHeader("Authorization");

        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            // 提取 token（去掉 "Bearer " 部分）
            String token = authorizationHeader.substring(7);


            // 这里可以添加 token 校验逻辑，例如使用 JWT 进行解码和验证
            // 你可以调用你的 token 校验方法，这里简单展示一下

            if (JwtUtils.verify(token)) {
                // 如果 token 合法，继续执行下一个过滤器或请求处理
                try {
                    TokenContext.setToken(token);
                    filterChain.doFilter(servletRequest, servletResponse);
                } finally {
                    // 清理 ThreadLocal
                    TokenContext.clear();
                }
            } else {
                // 如果 token 无效，返回 401 未授权错误
                ResponseResult<Object> objectResponseResult = ResponseResult.tokenError();
                String json = JSON.toJSONString(objectResponseResult);
                servletResponse.setCharacterEncoding("UTF-8");
                servletResponse.getWriter().write(json);
                return;
            }
        } else {
            // 如果请求头没有 token，返回 401 错误或进行其他处理
            ResponseResult<Object> objectResponseResult = ResponseResult.tokenMiss();
            String json = JSON.toJSONString(objectResponseResult);
            servletResponse.setCharacterEncoding("UTF-8");
            servletResponse.getWriter().write(json);
            return;
        }

    }
    @Override
    public void destroy() {
    }

    private boolean isWhitelisted(String requestURI) {
        // 这里我们检查是否存在精确匹配，或根据模式匹配（如 /public/*）来判断
        for (String pattern : customConfig.getWhitelist() ) {
            if (pattern.endsWith("/*")) {
                // 如果是 /public/* 这种模式，检查路径是否以 /public/ 开头
                if (requestURI.startsWith(pattern.substring(0, pattern.length() - 2))) {
                    return true;
                }
            } else {
                // 精确匹配
                if (requestURI.equals(pattern)) {
                    return true;
                }
            }
        }
        return false;
    }
}